package com.blue.common.utils.kaptcha.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blue.common.spring.SpringContextHolder;
import com.blue.common.utils.kaptcha.Constants;
import com.blue.common.utils.kaptcha.impl.DefaultKaptcha;

@WebServlet("/kaptchaServlet")
public class KaptchaServlet extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DefaultKaptcha kaptcha = SpringContextHolder.getBean(DefaultKaptcha.class) ;
		ServletOutputStream out = null ;
		try {
			response.setDateHeader("Expires", 0);
			response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			response.addHeader("Cache-Control", "post-check=0, pre-check=0");
			response.setHeader("Pragma", "no-cache");
			response.setContentType("image/jpeg");
			String capText = kaptcha.createText();
			request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
			BufferedImage bi = kaptcha.createImage(capText);
			out = response.getOutputStream();
			ImageIO.write(bi, "jpg", out);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(null != out) {
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
